บันทึกของบี

บันทึกการเดินทาง บนเส้นทางเดินแห่งชีวิต ของคนธรรมดาคนหนึ่ง

Ch5 Using Structs to Structure Related Data

2026-06-18 ใน The rust programming language 3rd edition(online document)
#[derive(Debug)]
struct Rectangle{
    width: u32,
    height: u32,
}
impl Rectangle{ // associated function
    fn canhold(&self, compare:&Rectangle)->bool{ //.method()
        compare.width<self.width && compare.height<self.height
    }
    fn area(&self)->u32{ //.method()
        self.width*self.height
    }
    fn square(dimension:u32) -> Self{ //::module
        Self{
            width: dimension,
            height: dimension
        }
    }
}
fn main(){
    let rect1=Rectangle{
        width:50,
        height:100,
    };
    let rect2=Rectangle{
        width:20,
        height:50,
    };
    println!("{}", rect2.canhold(&rect1));
    println!("{}", rect1.area());
    println!("{:#?}", Rectangle::square(20).area());
}